package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.inter.entity.agatewaytobeijing.JsonConstant;
import com.inter.entity.agatewaytobeijing.end.response.EndResponse;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newinterentity.aheadfinish.request.RequestAheadFinish;
import com.inter.entity.newinterentity.aheadfinish.request.RequestAheadFinishData;
import com.inter.entity.newinterentity.aheadfinish.request.RequestAheadFinishTradeData;
import com.inter.entity.newinterentity.aheadfinish.response.ResponseAheadFinish;
import com.inter.entity.newinterentity.aheadfinish.response.ResponseAheadFinishData;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.service.agatewaytobeijing.GatewayToBeijingService;
import com.inter.service.impl.AsyncOrderPlanService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 去北京做 3.22	提前结束套餐订单:2.0接口
 *
 * @author lm
 * @date 2019/3/4
 */

@RestController
@Api(description = "Ahead Closed Device Order")
@Slf4j
public class AheadFinishDeviceOrderController {
    @Autowired
    SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    AsyncOrderPlanService asyncOrderService;
    @Autowired
    GatewayToBeijingService toBeijingService;

    @CrossOrigin
    @RequestMapping(value = "/aheadClosedOrder", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "Ahead Closed Device Order", response = ResponseAheadFinish.class)
    public String aheadClosedOrder(@ApiParam @RequestBody RequestAheadFinish request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curTime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String requestStr = JSON.toJSONString(request);
        log.info("【提前结束订单】请求：" + requestStr);
        if (StringUtils.isBlank(request.getSign())) {
            log.info("请求报文不合法:sign为空");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String requestSign = request.getSign();
        if (null == request.getData()) {
            log.info("请求报文不合法:data为空");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        RequestAheadFinishData requestData = request.getData();
        if (StringUtils.isBlank(requestData.getPartnerCode()) || StringUtils.isBlank(requestData.getConnSeqNo()) || StringUtils.isBlank(requestData.getTradeTime()) || StringUtils.isBlank(requestData.getTradeType()) || null == requestData.getTradeData()) {
            log.info("请求报文不合法:data参数不合法");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String partnerCode = requestData.getPartnerCode();
        String secret = partnerService.findSecretByPartnerCode(partnerCode);
        String ConnSeqNo = requestData.getConnSeqNo();
        String tradeTime = requestData.getTradeTime();
        String token = requestData.getToken();
        String tradeType = requestData.getTradeType();
        String lang = requestData.getLang();
        RequestAheadFinishTradeData tradeData = requestData.getTradeData();
        if (StringUtils.isBlank(tradeData.getOrderId())) {
            log.info("请求报文不合法:orderId和deviceType参数不能为空！");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String orderId = tradeData.getOrderId();
        String str = JSON.toJSONString(requestData);
        String sign = utils.calculateSignature(str);
        /*验证签名*/
        if (!requestSign.equalsIgnoreCase(sign)) {
            log.info("签名验证失败");
            jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
            return jsonString;

        }

        /*响应*/
        ResponseAheadFinishData data = new ResponseAheadFinishData();
        ResponseAheadFinish response = new ResponseAheadFinish();
        /*签名验证通过,去做提前结束订单的活儿*/
        EndResponse aheadFinish = toBeijingService.aheadEndOrder(orderId, partnerCode, secret, "周期未结束需开启新的订单");
        /*成功提前结束的情况*/
        if (null != aheadFinish) {
            if (null != aheadFinish.getCode()) {
                if (JsonConstant.RET_CODE_0000.equals(aheadFinish.getCode())) {
                    /*成功提前结束订单*/
                    log.info("提前结束订单：" + orderId + "：成功！");
                    /*提前结束成功*/
                    data.setConnSeqNo(ConnSeqNo);
                    data.setTradeType(tradeType);
                    data.setTradeTime(curTime);
                    data.setPartnerCode(partnerCode);
                    data.setToken(token);
                    data.setTradeRstCode(1000);
                    if (lang.equals("en")) {
                        data.setTradeRstMessage("success");
                    } else {
                        data.setTradeRstMessage("成功");
                    }
                    response.setData(data);
                    response.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                    jsonString = JSON.toJSONString(response);
                    log.info("响应报文：" + jsonString);
                    return jsonString;
                } else {
                    //发送异常邮件：
                    asyncOrderService.SendMail("", "", orderId, "提前结束订单", aheadFinish.getMessage());
                    log.info(orderId + "【正在使用订单】提前结束失败，原因：" + aheadFinish.getMessage());
                }

            } else {
                log.info("提前结束订单：" + orderId + "：失败！");
                /*接口响应原因导致的提前结束订单失败：发送异常邮件*/
                asyncOrderService.SendMail("", "", orderId, "提前结束订单", "接口连接超时或其他原因的提前结束失败");
                //记录异常操作到数据库：
                log.info(orderId + "：【正在使用订单】因接口连接超时或其他原因提前结束失败");
            }
        } else {
            log.info("提前结束订单：" + orderId + "：失败！");
            /*接口响应原因导致的提前结束订单失败：发送异常邮件*/
            asyncOrderService.SendMail("", "", orderId, "提前结束订单", "接口连接超时或其他原因的提前结束失败");
            //记录异常操作到数据库：
            log.info(orderId + "：【正在使用订单】因接口连接超时或其他原因提前结束失败");
        }
        /*失败的响应*/
        data.setConnSeqNo(ConnSeqNo);
        data.setTradeType(tradeType);
        data.setTradeTime(curTime);
        data.setPartnerCode(partnerCode);
        data.setToken(token);
        data.setTradeRstCode(9998);
        if (lang.equals("en")) {
            data.setTradeRstMessage("Failure to close the order ahead of schedule ！");
        } else {
            data.setTradeRstMessage("提前结束订单失败！");
        }
        response.setData(data);
        response.setSign(MD5.calcMD5(JSON.toJSONString(data)));
        jsonString = JSON.toJSONString(response);
        log.info("响应报文：" + jsonString);
        return jsonString;
    }
}
